<template>
  <Modal v-model="open" :closeOnMask="false" hasDivider hasCloseIcon>
    <template #header><Lang zh="字典管理" en="Dictionary"/></template>
    <div style="width: 320px">
      <Form :model="form" :rules="rules" ref="form" labelWidth="90">
        <FormItem :label="$t('中文名称','ChineseName')" prop="name">
          <Input type="text" v-model="form.name"/>
        </FormItem>
        <FormItem :label="$t('英文名称','EnglishName')" prop="en">
          <Input type="text" v-model="form.en"/>
        </FormItem>
        <FormItem :label="$t('排序','Rank')" prop="rank">
          <NumberInput  v-model="form.rank"/>
        </FormItem>
        <FormItem :label="$t('编码','Code')" prop="sn" required>
          <Input type="text" v-model="form.sn" :readonly="form.type=='dict'&&form.id"/>
        </FormItem>
      </Form>
    </div>
    <template #footer>
      <Button @click="open=false"><Lang zh="取消"/></Button>
      <Button :loading="loading" color="primary" @click="saveOrUpdate"><Lang zh="确认"/></Button>
    </template>
  </Modal>
</template>
<script>
import {ajax, util,useKeyDown} from 'framework'
import {message} from 'heyui'
import {$t} from 'i18n'
export default {
  name: 'DictionaryDialog',
  emits: ['change'],
  props:{
    dictType:String
  },
  data: function () {
    let keydown=useKeyDown()
    keydown.on('Escape',()=>{
      this.open=false
    })
    return {
      open: false,
      loading: false,
      isAdd: false,
      form: {
        id: null,
        name: null,
        en:null,
        rank: null,
        sn: null,
        type: null,
      },
      //验证规则
      rules: {}
    }
  }, methods: {
    $t,
    show(primary) {
      this.loading = true
      util.clean(this.form)
      if (primary) {//show edit
        this.isAdd = false
        ajax.get("dictionary/detail", primary).then(r => {
          this.form = r.data
          let name=r.data.name
          if (name&&name.startsWith('{')&&name.endsWith('}')){
            let langMap=JSON.parse(name)
            this.form.name=langMap.zh
            this.form.en=langMap.en
          }
          this.loading = false;
          this.open = true;
        })
      } else {
        this.isAdd = true
        //show add
        this.form.type=this.dictType

        this.open = true
        this.loading = false
      }
    },
    saveOrUpdate() {
      var validResult = this.$refs.form.valid();
      if (validResult.result) {
        this.loading = true
        let data=Object.assign({},this.form)
        if (data.en){
          data.name=JSON.stringify({zh:data.name,en:data.en})
        }
        delete data.en
        ajax.post(this.isAdd ? 'dictionary/add' : 'dictionary/save', data).then(r => {
          this.open = false;
          message($t("已保存"))
          this.$emit("change", r.data)
        }).catch(e => {
          this.loading = false
         // this.$Message(e.message)
        })
      }
    }
  }
}
</script>
